package com.lianyu.wangyiyun.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.lianyu.wangyiyun.databinding.FragmentSearchBinding;
import com.lianyu.wangyiyun.databinding.MusictItemBinding;
import com.lianyu.wangyiyun.model.Mp3Info;
import com.lianyu.wangyiyun.model.MusicListViewModel;
import com.lianyu.wangyiyun.service.MusicService;
import com.lianyu.wangyiyun.utils.KeyboardChangeListener;
import com.lianyu.wangyiyun.utils.MyRetrofit;
import com.lianyu.wangyiyun.utils.MyUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Chen Yuguang
 * @date 2021/5/14 22:37
 */
public class SearchFragment extends AbstractLazyFragment {

    private RefreshLayout refreshLayout;
    private MusicListViewModel musicListViewModel;
    private MusicListViewModel mainMusicListViewModel;
    private KeyboardChangeListener keyboardChangeListener;
    /**
     * 上次搜索文本
     */
    private String query;

    public RefreshLayout getRefreshLayout() {
        return refreshLayout;
    }

    private final DiffUtil.ItemCallback<Mp3Info> diffCallback =
            new DiffUtil.ItemCallback<Mp3Info>() {

                @Override
                public boolean areItemsTheSame(@NonNull Mp3Info oldItem, @NonNull Mp3Info newItem) {
                    return oldItem.getId() == newItem.getId();
                }

                @Override
                public boolean areContentsTheSame(@NonNull Mp3Info oldItem, @NonNull Mp3Info newItem) {
                    return oldItem.equals(newItem);
                }
            };

    private final RecyclerAdapter recyclerAdapter = new RecyclerAdapter();

    public void setList(List<Mp3Info> list) {
        musicListViewModel.getMusicLiveData().setValue(list);
    }

    public void addList(List<Mp3Info> list) {
        List<Mp3Info> newList = new ArrayList<>();
        newList.addAll(recyclerAdapter.getCurrentList());
        newList.addAll(list);
        musicListViewModel.getMusicLiveData().setValue(newList);
    }

    @Override
    protected View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        FragmentSearchBinding fragmentSearchBinding = FragmentSearchBinding.inflate(inflater, container, false);
        Activity activity = getActivity();
        int statusHeight = 0;
        if (activity != null) {
            statusHeight = MyUtils.getStatusBarHeight(activity);
        }
        fragmentSearchBinding.topBar.setPadding(0, statusHeight, 0, 0);
        SearchView searchView = fragmentSearchBinding.searchView;
        //设置searchView处于展开状态
        searchView.setIconified(false);
        //当展开无输入内容的时候，没有关闭的图标
        searchView.onActionViewExpanded();
        //搜索监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            //提交搜索
            @Override
            public boolean onQueryTextSubmit(String query) {
                refreshLayout.autoRefresh();
                return false;
            }

            //搜索框文本改变
            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        //软键盘呼出监听
        keyboardChangeListener = new KeyboardChangeListener(activity, isShow -> {
            if (!isShow) {
                searchView.clearFocus();
            }
        });
        //返回按钮点击事件
        fragmentSearchBinding.toolbar.setNavigationOnClickListener(v -> {
            //获得fragment管理者
            FragmentManager fragmentManager = getFragmentManager();
            if (fragmentManager != null) {
                //新建事务
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                //移除本界面
                transaction.remove(SearchFragment.this);
                Fragment mainFragment = fragmentManager.findFragmentByTag("main");
                if (mainFragment != null) {
                    //显示主界面
                    transaction.show(mainFragment);
                    //提交事务
                    transaction.commit();
                }
            }
        });
        RecyclerView musicRecyclerView = fragmentSearchBinding.musicRecyclerView;
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置布局管理者（竖向的线性布局）
        musicRecyclerView.setLayoutManager(linearLayoutManager);
        //设置适配器
        musicRecyclerView.setAdapter(recyclerAdapter);
        TextView nilView = fragmentSearchBinding.nilView;
        refreshLayout = fragmentSearchBinding.smartRefreshLayout;
        //是否在刷新的时候禁止列表的操作
        refreshLayout.setDisableContentWhenRefresh(true);
        //是否在加载的时候禁止列表的操作
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            //判断搜索框文本是否为空
            String query = searchView.getQuery().toString();
            if (!query.isEmpty()) {
                //启动搜索，从0开始访问网络获取数据
                this.query = query;
                MyRetrofit.get(this, searchView.getQuery().toString(), 0);
            }
        });
        //上拉加载更多搜索结果
        refreshLayout.setOnLoadMoreListener(refreshLayout -> MyRetrofit.get(this, query, recyclerAdapter.getCurrentList().size()));
        musicListViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
        //将viewModel与recyclerView的适配器列表绑定在一起
        musicListViewModel.getMusicLiveData().observe(this, list -> {
            if (list.size() == 0) {
                //显示空布局
                if (nilView.getVisibility() == View.GONE) {
                    nilView.setVisibility(View.VISIBLE);
                }
            } else {
                if (nilView.getVisibility() == View.VISIBLE) {
                    nilView.setVisibility(View.GONE);
                }
            }
            //提交数据给适配器
            recyclerAdapter.submitList(list);
        });
        FragmentActivity fragmentActivity = getActivity();
        if (fragmentActivity != null) {
            mainMusicListViewModel = new ViewModelProvider(fragmentActivity, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
        }
        return fragmentSearchBinding.getRoot();
    }

    @Override
    public void onDestroy() {
        keyboardChangeListener.removeListener();
        super.onDestroy();
    }

    private class RecyclerAdapter extends ListAdapter<Mp3Info, RecyclerAdapter.ViewHolder> {

        protected RecyclerAdapter() {
            super(diffCallback);
        }

        //创建视图
        @Override
        public @NonNull
        RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            MusictItemBinding musictItemBinding = MusictItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new RecyclerAdapter.ViewHolder(musictItemBinding);
        }

        //数据绑定
        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            holder.title.setText(getCurrentList().get(position).getTitle());
            holder.artist.setText(getCurrentList().get(position).getArtist());
            holder.itemView.setOnClickListener(v -> {
                //获取mainActivity的viewModel值（点击的播放列表）
                List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
                //获取mainActivity的viewModel值（播放的位置）
                Integer nowPosition = mainMusicListViewModel.getPositionLiveData().getValue();
                if (mp3Infos == null) {
                    mp3Infos = new ArrayList<>();
                } else {
                    mp3Infos = new ArrayList<>(mp3Infos);
                }
                if (nowPosition == null) {
                    nowPosition = -1;
                }
                //向列表添加点击的item(添加的位置为当前播放位置+1）
                mp3Infos.add(nowPosition + 1, getCurrentList().get(position));
                //重新设置要传给mainActivity的viewModel值（点击的播放列表）
                mainMusicListViewModel.getMusicLiveData().setValue(mp3Infos);
                //重新设置要传给mainActivity的viewModel值（播放的位置）
                mainMusicListViewModel.getPositionLiveData().setValue(nowPosition + 1);
                Intent serviceIntent = new Intent(getContext(), MusicService.class);
                Mp3Info mp3Info = getCurrentList().get(position);
                //发送url给服务播放
                serviceIntent.putExtra("url", mp3Info.getUrl());
                serviceIntent.putExtra("title", mp3Info.getTitle());
                serviceIntent.putExtra("artist", mp3Info.getArtist());
                Context context = getContext();
                if (context != null) {
                    //启动播放服务
                    context.startService(serviceIntent);
                }
            });
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView title, artist;

            public ViewHolder(@NonNull MusictItemBinding musictItemBinding) {
                super(musictItemBinding.getRoot());
                title = musictItemBinding.title;
                artist = musictItemBinding.artist;
            }
        }

    }

}
